import React, { useState, useEffect } from 'react';
import ReactDOM from 'react-dom';
import {
  BrowserRouter as Router,
  Routes,
  Route,
  Navigate,
} from 'react-router-dom';
import LoginPage from './LoginPage';
import RegisterPage from './RegisterLink';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { message, Spin } from 'antd';
import Test from './Test';
import 'katex/dist/katex.min.css';

const root = document.getElementById('root');

const Loading = () => {
  return (
    <div
      style={{
        height: '100vh',
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
      }}>
      <Spin
        size='large'
        tip='正在获取登录状态，请稍后...'
      />
    </div>
  );
};
const Root = () => {
  const [loading, setLoading] = useState(false);
  const [loggedIn, setLoggedIn] = useState(false);
  const isTokenExpired = async () => {
    setLoading(true);
    const token = sessionStorage.getItem('token');
    if (!token) {
      // 没有令牌，说明用户未登录
      setLoggedIn(false);
    }

    try {
      const response = await fetch('http://localhost:29157/api/users/isLogin', {
        method: 'POST', // 或 "GET"，取决于您的 API
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          token: token,
        }),
      });

      if (!response.ok) {
        message.error('网络错误');
      }

      const data = await response.json();
      console.log(data.data.data);
      if (data.data.data && data.data.data === '用户已登录') {
        console.log('用户已登录');
        setLoggedIn(true);
      } else {
        // 令牌无效
        setLoggedIn(false);
      }
    } catch (error) {
      console.error('检查令牌时出错:', error);
      // 默认情况下，如果发生错误，则认为令牌已过期
      setLoggedIn(false);
    }
    setLoading(false);
  };

  useEffect(() => {
    isTokenExpired();
  }, []);
  if (loading) {
    return (
      <div
        style={{
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          height: '100%',
        }}>
        <Spin
          tip={'正在查询登录状态请稍后'}
          size={'large'}
        />
      </div>
    );
  } else {
    return (
      <Router>
        <Routes>
          <Route
            path='/register'
            element={<RegisterPage />}
          />
          <Route
            path='/*'
            element={
              loggedIn ? <App /> : <LoginPage setLoggedIn={setLoggedIn} />
            }
          />
        </Routes>
      </Router>
    );
  }
};
ReactDOM.render(
  <React.StrictMode>
    <Root />
  </React.StrictMode>,
  root
);

reportWebVitals();
